import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routes'
import store from '@/store'
import { message } from 'ant-design-vue'
import loading from '@/components/Loading/Loading'

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

let unLoading = null
const safeName = ['user-login', 'error']
router.beforeEach(async (to, from, next) => {
  //profile三种情况,null:初始的未知状态,false:获取用户信息失败返回的false，表示未登录的状态,obj:登陆成功的状态
  let profile = store.state.user.profile
  //如果去的不是login与404页面,且没有用户信息
  if (!safeName.includes(to.name) && !profile) {
    if (profile === null) {
      //profile为null的情况 不确定是否未登录 先获取信息
      unLoading = loading()
      profile = await store.dispatch('user/getProfile')
    }
    if (!profile) {
      //profile为false的情况 确定未登录
      message.warn('请您先登录~')
      next(`/user/login?to=${encodeURIComponent(to.fullPath)}`)
      return
    }
  }
  next()
})

router.afterEach((to, from) => {
  //取消loading
  if (unLoading) {
    unLoading()
    unLoading = null
  }
  //修改标题
  let title = to.meta.title
  document.title = title ? `${title}-FastBee物联网系统` : `FastBee物联网系统`

  //记录历史记录存储tabs
  if (to.meta.level === 3) {
    store.commit('tabs/setHistory', {
      name: to.name,
      path: to.path,
      title: to.meta.title,
    })
  }
})

export default router
